package com.blockmeta.bbs.minemodule.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.net.callback.FileUploadCallBack;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.ImageTools;
import com.blockmeta.bbs.baselibrary.utils.LoadPicUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.arouter.RouterConstant;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.arouter.interfaces.IThirdLoginDataProvider;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.pojo.UserInfo;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.pojo.LoginPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.AppCode;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.businesslibrary.util.Update2QiniuCloud;
import com.blockmeta.bbs.businesslibrary.widget.CircleImageView;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.net.NetApi;
import com.blockmeta.bbs.minemodule.pojo.UserPOJO;
import com.blockmeta.bbs.minemodule.popup.MyBottomPopupWindow;
import com.blockmeta.bbs.minemodule.umeng.UMLoginListener;
import com.google.gson.Gson;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.suke.widget.SwitchButton;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhy.http.okhttp.OkHttpUtils;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.model.CropOptions;
import org.devio.takephoto.model.TImage;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.model.TakePhotoOptions;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;


/**
 * Created by author on 2018/1/4.
 */
@Route(path = RouterPath.MINE_SETTING_ACTIVITY, extras = RouterConstant.EXTRAL_LOGIN)
public class MineSettingActivity extends BaseActivity implements View.OnClickListener {
    private View v;
    private RelativeLayout click1;
    private RelativeLayout click2;
    private RelativeLayout click3;
    private RelativeLayout click4;
    private RelativeLayout click5;
    private RelativeLayout click6;
    private Button quit;
    private CircleImageView mine1;
    private TextView mine2;
    private TextView mine3;
    private TextView mine4;
    private TextView mine5;
    private MyBottomPopupWindow popupWindow;
    private String md5;
    private RelativeLayout weixin, qq, weibo;
    private TextView mTvWeixin, mTvQQ, mTvWeibo;
    private UMShareAPI mUMShareAPI;
    //登陆平台 weixin,qq,weibo
    private String mPicToken;
    private String type;
    private String uClickEvent = "none";
    private UserInfo mUserInfo;

    @Override
    protected boolean showTitle() {
        return true;
    }

    @Override
    public View setView() {
        setTitleText("个人设置");
        v = LayoutInflater.from(mContext).inflate(R.layout.activity_minesetting, null);
        EventBus.getDefault().register(this);
        initData();
        return v;
    }

    private void initData() {
        mUMShareAPI = UMShareAPI.get(this);
        click1 = (RelativeLayout) v.findViewById(R.id.minesettin_click1);
        click2 = (RelativeLayout) v.findViewById(R.id.minesettin_click2);
        click3 = (RelativeLayout) v.findViewById(R.id.minesettin_click3);
        click4 = (RelativeLayout) v.findViewById(R.id.minesettin_click4);
        click5 = (RelativeLayout) v.findViewById(R.id.minesettin_click5);
        click6 = (RelativeLayout) v.findViewById(R.id.minesettin_click6);


        weixin = v.findViewById(R.id.minesetting_weixin);
        qq = v.findViewById(R.id.minesetting_QQ);
        weibo = v.findViewById(R.id.minesetting_weibo);

        mTvWeixin = v.findViewById(R.id.minesetting_tv_weixin);
        mTvQQ = v.findViewById(R.id.minesetting_tv_QQ);
        mTvWeibo = v.findViewById(R.id.minesetting_tv_weibo);

        quit = (Button) v.findViewById(R.id.btn_quit);


        TextView hint = v.findViewById(R.id.mine_setting_tv_hint);
        View divider = v.findViewById(R.id.mine_setting_v_divider);

        click1.setOnClickListener(this);
        click2.setOnClickListener(this);
        click3.setOnClickListener(this);
        click4.setOnClickListener(this);
        click5.setOnClickListener(this);
        click6.setOnClickListener(this);

        quit.setOnClickListener(this);

        mine1 = (CircleImageView) v.findViewById(R.id.minesettin_1);
        mine2 = (TextView) v.findViewById(R.id.minesettin_2);
        mine3 = (TextView) v.findViewById(R.id.minesettin_3);
        mine4 = (TextView) v.findViewById(R.id.minesettin_4);
        mine5 = (TextView) v.findViewById(R.id.minesettin_5);

        LoadPicUtil.loadWithPicasso(mine1, AccountHelper.getUserPhonePOJO().getLogo());
        String phone = AccountHelper.getUserPhonePOJO().getMobile() == null ? " " : AccountHelper.getUserPhonePOJO().getMobile();
        mine2.setText(AccountHelper.getUserPhonePOJO().getNickName());
        mine3.setText(AccountHelper.getUid());
        mine4.setText(phone);
        mine5.setText(AccountHelper.getUserPhonePOJO().getEmail());

        getUserInformation();
    }


    private void switchToggle(boolean checked, SwitchButton switchButton, SwitchButton.OnCheckedChangeListener listener) {
        switchButton.setOnCheckedChangeListener(null);
        switchButton.setChecked(checked);
        switchButton.setOnCheckedChangeListener(listener);
    }

    private void getUserInformation() {
        OkHttpUtils.get()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, null))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.USER_INFO_BIND)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        UserPOJO pojo = new Gson().fromJson(response, UserPOJO.class);
                        weixin.setOnClickListener(MineSettingActivity.this);
                        qq.setOnClickListener(MineSettingActivity.this);
                        weibo.setOnClickListener(MineSettingActivity.this);
                        if (pojo == null || pojo.bindInfo == null) {
                            return;
                        }
                        if (pojo.bindInfo.weixin != null) {
                            mTvWeixin.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvWeixin.setText("已绑定");
                            weixin.setOnClickListener(null);
                        } else {
                            mTvWeixin.setTextColor(getResources().getColor(R.color.red_EE4A45));
                            mTvWeixin.setText("未绑定");
                        }
                        if (pojo.bindInfo.qq != null) {
                            mTvQQ.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvQQ.setText("已绑定");
                            qq.setOnClickListener(null);
                        } else {
                            mTvQQ.setTextColor(getResources().getColor(R.color.red_EE4A45));
                            mTvQQ.setText("未绑定");
                        }
                        if (pojo.bindInfo.weibo != null) {
                            mTvWeibo.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvWeibo.setText("已绑定");
                            weibo.setOnClickListener(null);
                        } else {
                            mTvWeibo.setTextColor(getResources().getColor(R.color.red_EE4A45));
                            mTvWeibo.setText("未绑定");
                        }
                    }
                });
    }

    @Override
    public void onClick(View view) {
        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri imageUri = Uri.fromFile(file);
        int i = view.getId();
        if (i == R.id.minesettin_click1) {
            //头像
            showIconChoice();
            uClickEvent = "icon";

        } else if (i == R.id.minesettin_click2) {
            //名字
            activityStartActivity(mContext, EditUserInfoActivity.class);
            uClickEvent = "name";


        } else if (i == R.id.minesettin_click3) {
        } else if (i == R.id.minesettin_click4) {
            //绑定手机
            if (AccountHelper.getUserPhonePOJO().getMobile().isEmpty()) {
                RouterHelper.startActivity(this, RouterPath.BIND_ACCOUNT_PHONE_ACTIVITY);
            } else {
                ToastUtil.show("您已经绑定过手机号了");
            }
            uClickEvent = "bindPhone";


        } else if (i == R.id.minesettin_click5) {
            ToastUtil.show("暂不支持修改，敬请期待");

        } else if (i == R.id.minesettin_click6) {
            //修改密码
            RouterHelper.startActivity(this, RouterPath.MODIFY_PWD_ACTIVITY);
            uClickEvent = "changePassWord";

        } else if (i == R.id.btn_quit) {
            quitLogin();
            uClickEvent = "loginout";

        } else if (i == R.id.popup_tx_2) {
            //相册
            getTakePhoto().onPickFromGalleryWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_3) {
            //拍照
            getTakePhoto().onPickFromCaptureWithCrop(imageUri, getCropOptions());

        } else if (i == R.id.popup_tx_4) {
            //取消
            popupWindow.dismiss();

        } else if (i == R.id.minesetting_weixin) {
            //微信绑定
            type = "weixin";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, umLoginListener);
            uClickEvent = "bindWeixin";


        } else if (i == R.id.minesetting_QQ) {
            //QQ绑定
            type = "qq";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, umLoginListener);
            uClickEvent = "bindQQ";


        } else if (i == R.id.minesetting_weibo) {
            //微博绑定
            type = "weibo";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, umLoginListener);
            uClickEvent = "bindWeiBo";

        } else {
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("mineClick", uClickEvent);
        map.put("uid", AccountHelper.getUserPhonePOJO() == null ? "0" : AccountHelper.getUid());
        UmengEvent.eventStatistics(mContext, Constant.U_MINE_MYSETTING, map);
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    /**
     * 三方登陆成功的回调信息
     */
    UMLoginListener umLoginListener = new UMLoginListener() {
        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            String stoken = map.get("accessToken");
            String openId = map.get("openid") == null ? map.get("uid") : map.get("openid");
            String unionId = map.get("unionid");
            String nickName = map.get("name");
            String avatar = map.get("iconurl");
            IThirdLoginDataProvider provider = RouterHelper.getProvider(RouterPath.THIRD_LOGIN_DATA_PROVIDER);
            provider.setUid(openId);
            provider.setUnionid(unionId);
            provider.setName(nickName);
            provider.setIconUrl(avatar);
            provider.setType(type);
            provider.setStoken(stoken);
            Bind(openId, unionId, nickName, avatar, type, 0, AccountHelper.getUid(), stoken);
        }
    };

    /**
     * 绑定三方账号
     *
     * @param openId   三方登陆的唯一标识
     * @param nickName 昵称
     * @param avatar   头像链接
     * @param type     使用哪个三方平台登陆的 weixin qq weibo
     * @param register 推迟绑定时register=1 其它=0
     * @param uid      账号id
     */
    private void Bind(String openId, String unionId, String nickName, String avatar, final String type, int register, String uid, String stoken) {
        HashMap<String, String> checkMap = new HashMap<>();

        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);

        checkMap.put("openid", openId);
        checkMap.put("unionid", unionId);
        checkMap.put("nickname", nickName);
        checkMap.put("avatar", avatar);
        checkMap.put("type", type);
        checkMap.put("stoken", stoken);
        checkMap.put("register", register + "");
        checkMap.put("uid", AccountHelper.getUid());
        checkMap.put("device_id", DeviceUtil.getIMEI());
        checkMap.put("product_code", myAppCode);
        checkMap.put("source", "app");
        checkMap.put("bind_type", "1");

        RetrofitFactory.getRootRetrofit().create(NetApi.SocialBind.class)
                .bindSocial(RequestBody.create(NetApi.sMediaType, new Gson().toJson(checkMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<LoginPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<LoginPOJO>(mContext) {
                    @Override
                    public void onNext(LoginPOJO loginPOJO) {
                        if (type.equals("weixin")) {
                            mTvWeixin.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvWeixin.setText("已绑定");
                            weixin.setOnClickListener(null);
                        } else if (type.equals("qq")) {
                            mTvQQ.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvQQ.setText("已绑定");
                            qq.setOnClickListener(null);
                        } else {
                            mTvWeibo.setTextColor(getResources().getColor(R.color.black_999999));
                            mTvWeibo.setText("已绑定");
                            weibo.setOnClickListener(null);
                        }
                        //三方账号绑定是否完成
                        isTaskComplete(11, null);
                    }
                });
    }

    private void showIconChoice() {
        popupWindow = new MyBottomPopupWindow(mContext);
        popupWindow.tx2.setText("相册");
        popupWindow.tx3.setText("拍照");
        popupWindow.tx2.setOnClickListener(this);
        popupWindow.tx3.setOnClickListener(this);
        popupWindow.tx4.setOnClickListener(this);

        popupWindow.showPopupWindow();

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void LoginUI(MsgSuccess message) {
        if ("editName".equals(message.msg)) {
            mine2.setText(message.tag);
            //判断任务是否完成 修改用户名
            isTaskComplete(9, null);
        } else if ("bindPhone".equals(uClickEvent) && "LOGIN".equals(message.msg)) {
            //绑定手机号
            isTaskComplete(10, null);
        }
    }

    /**
     * 退出登陆
     */
    private void quitLogin() {
        AccountHelper.doLoginOut();
        RetrofitFactory.invalidateRetrofitClient();
        ThrioNavigator.pop(null, false);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        mUMShareAPI.release();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        TImage image = result.getImage();
        final String compressPath = image.getOriginalPath();


        try {
//            final int[] fileSize = ImageTools.getFileSize(compressPath);
//            JSONObject jsonObject = new JSONObject();
//            jsonObject.put("w", fileSize[0] + "");
//            jsonObject.put("h", fileSize[1] + "");

            final String needDeleteFileUrl = compressPath;
            Update2QiniuCloud.postFileToNet(mContext, "avator", needDeleteFileUrl, new FileUploadCallBack() {
                @Override
                public void fail(String msg) {
                    ProgressBarUtil.dismissProgress(mContext);
                    ToastUtil.show("上传失败，请稍后重试");
                }

                @Override
                public void progress(int progress) {
                }

                @Override
                public void success(String s) {
                    //删除发送的压缩后保存的图片
                    putQiNiuKey(s);
                }
            });


        } catch (Exception e) {
            LogUtils.d("uploadimage error " + e.getMessage());
        }

        popupWindow.dismiss();

    }

    private void putQiNiuKey(final String picName) {
        HashMap<String, Object> checkMap = new HashMap<>();
        checkMap.put("uid", AccountHelper.getUidInt());
        checkMap.put("logo", picName);
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(new Gson().toJson(checkMap))
                .url(NetConstant.USER_INFO_EDIT)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (code == 200) {
                            LoadPicUtil.loadWithPicasso(mine1, picName);
                            UserPhonePOJO userPhonePOJO = AccountHelper.getUserPhonePOJO();
                            userPhonePOJO.setLogo(picName);
                            AccountHelper.setUserPhonePOJO(userPhonePOJO);
                            ToastUtil.show("头像修改成功");
                        }
                    }
                });

    }


    private void configTakePhotoOption(TakePhoto takePhoto) {
        TakePhotoOptions.Builder builder = new TakePhotoOptions.Builder();
        //选择自带相册 否
        builder.setWithOwnGallery(false);
        //纠正旋转角度
        builder.setCorrectImage(true);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    //裁剪
    private CropOptions getCropOptions() {
        int height = Integer.parseInt("150");
        int width = Integer.parseInt("150");
        //TokePhoto裁剪工具
        boolean withWonCrop = true;
        CropOptions.Builder builder = new CropOptions.Builder();
        builder.setOutputX(width).setOutputY(height);
        builder.setWithOwnCrop(withWonCrop);
        return builder.create();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mUMShareAPI.onActivityResult(requestCode, resultCode, data);
    }
}
